|
Technical Q&AJava 12 - Using
|
import java.awt.Frame; import java.awt.FileDialog; import java.io.File; import java.io.IOException; public class ExecTest extends Frame { public static void main(String[ ] args) { new ExecTest(); System.exit(0); } public ExecTest() { String browserName; String url = "http://developer.apple.com/java/"; //Set up a FileDialog for the user to locate the browser to use. FileDialog fileDialog = new java.awt.FileDialog(this); fileDialog.setMode(FileDialog.LOAD); fileDialog.setTitle("Choose the browser to use:"); fileDialog.setVisible(true); //Retrieve the path information from the dialog and verify it. String resultPath = fileDialog.getDirectory(); String resultFile = fileDialog.getFile(); if(resultPath != null && resultPath.length()!= 0 && resultFile != null && resultFile.length() != 0) { File file = new File(resultPath + resultFile); if(file != null) { browserName = file.getPath(); try { //Launch the browser and pass it the desired URL Runtime.getRuntime().exec(newString[ ] {browserName, url}); } catch (IOException exc) { exc.printStackTrace(); } } } } } |
This example should be refined, if used in a real setting, to cache the browser information and only ask the user if the cached browser could not be located.
A more sophisticated approach that would not require the user to choose the browser could use JConfig to obtain the default browser information.
As an alternative to JConfig for the sole purpose of opening a URL in the user's
default browser, one should consider BrowserLauncher
by Eric Albert. BrowserLauncher
is
a Java class designed to allow programmers to open a user's default web browser entirely
through Java, without requiring that any supplemental libraries be present and without
stepping outside of JDK 1.1. BrowserLauncher
is free for commercial and non-commercial
use.